//
//  ASHomeSearchController.m
//  AvatarShow
//
//  Created by xunruiIOS on 2021/4/28.
//

#import "ASHomeSearchController.h"
#import "ASNoneView.h"
#import "ASSearchHeadView.h"
#import "ASHomeSearchListVC.h"
#import "ASHomeApi.h"
#import "ASSearchHotCell.h"
#import "ASSearchTitleView.h"
#import "ASSearchHotModel.h"

@interface ASHomeSearchController () <UIGestureRecognizerDelegate,UITableViewDelegate,UITableViewDataSource>

@property (strong, nonatomic) NSMutableArray *hotArr;
@property (strong, nonatomic) NSMutableArray *historyData;
@property (strong, nonatomic) NSMutableArray *hotTitleArr;

@property (strong, nonatomic) ASSearchHeadView *headView;
@property (strong, nonatomic) UITableView *hotTable;         //tableView
@property (strong, nonatomic) ASNoneView *noneView;
@property (assign, nonatomic) CGFloat historyHeight;

@end

@implementation ASHomeSearchController

- (void)dealloc{
    FELog(@"IGSearchConteroller 页面释放");
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBarHidden = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = BACKGROUND_COLOR;
    self.navigationController.interactivePopGestureRecognizer.delegate = self;
    [self.view addSubview:self.hotTable];
    [self.view addSubview:self.headView];
    [self.hotTable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsMake(RectNavAndStatusHight, 0, 0, 0));
    }];
    [self loadMainData];
    
    NSArray *hisArr = [[NSUserDefaults standardUserDefaults]objectForKey:SEARCHHISTORYKEY];
    self.historyData = [NSMutableArray arrayWithArray:hisArr];
    [self crateHistoryHeight];
    if (self.historyData.count > 0) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.hotTable reloadData];
        });
    }
    // Do any additional setup after loading the view.
}

- (ASSearchHeadView *)headView{
    if (!_headView) {
        _headView = [[ASSearchHeadView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, Height_NavBar)];
        _headView.backgroundColor = MAIN_NAV_COLOR;
        [_headView.searchText becomeFirstResponder];

        @weakify(self);
        _headView.clickSearchBlock = ^(NSString * _Nonnull searchContent) {
            @strongify(self);
            if ([searchContent isNotBlank]) {
                if (searchContent.length > 0) {
                    [self searchContent:searchContent];
                    return;
                }
            }
            [MBProgressHUD showError:@"请输入搜索内容"];
        };
    }
    return _headView;
}

- (UITableView *)hotTable{
    if (!_hotTable) {
        _hotTable = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
        _hotTable.delegate = self;
        _hotTable.dataSource = self;
        _hotTable.backgroundColor = BACKGROUND_COLOR;
        _hotTable.separatorStyle = UITableViewCellSeparatorStyleNone;
        _hotTable.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
        _hotTable.showsVerticalScrollIndicator = NO;
        _hotTable.showsHorizontalScrollIndicator = NO;
        [_hotTable registerClass:[ASSearchHotCell class] forCellReuseIdentifier:ASSearchHotCellStr];
//        [_hotTable registerClass:[MWSearchTableViewCell class] forCellReuseIdentifier:MWSearchTableViewCellStr];
        [_hotTable registerClass:[ASSearchTitleView class] forHeaderFooterViewReuseIdentifier:ASSearchTitleViewStr];
    }
    return _hotTable;
}

- (ASNoneView *)noneView{
    if (!_noneView) {
        _noneView = [[ASNoneView alloc]initWithFrame:CGRectZero];
        [_noneView.logoImage setImage:[UIImage imageNamed:@"icon_empty"]];
        _noneView.titleLab.text = @"暂时没有关联数据";
    }
    return _noneView;
}

#pragma mark - LoadData
- (void)loadMainData{
    [MBProgressHUD showMessage:@"加载中..."];
    [ASHomeApi loadHotSearchDataCompletion:^(ASBaseModel *  _Nonnull result) {
        [MBProgressHUD hideHUD];
        if (result.state.intValue == 1) {
            [self.hotArr removeAllObjects];
            self.hotArr = [NSMutableArray new];
            [self.hotTitleArr removeAllObjects];
            self.hotTitleArr = [NSMutableArray new];
            [self.hotArr addObjectsFromArray:result.resultArr];
            for (ASSearchHotModel *subModel in self.hotArr) {
                [self.hotTitleArr addObject:subModel.word];
            }
            [self.hotTable reloadData];
        }else{
            [MBProgressHUD showError:result.errorMsg];
        }
    } failure:^(NSError * _Nonnull error) {
        [MBProgressHUD hideHUD];
        [MBProgressHUD showError:FENETERROR];
    }];
}


- (void)searchContent:(NSString *)content{
    ASHomeSearchListVC *listVC = [ASHomeSearchListVC new];
    listVC.searchContent = content;
    listVC.historyArr = self.historyData;
    listVC.hasUp = YES;
    listVC.type = 1;
    [self.navigationController pushViewController:listVC animated:NO];
    
    @weakify(self);
    listVC.willBackBlock = ^(NSMutableArray * _Nonnull hisArr) {
        @strongify(self);
        self.historyData = hisArr;
//        [self.hicCell createCellHeightWithTagArr:self.historyData];
        [self.hotTable reloadData];
        
        [[NSUserDefaults standardUserDefaults]setObject:[NSArray arrayWithArray:hisArr] forKey:SEARCHHISTORYKEY];
        [[NSUserDefaults standardUserDefaults]synchronize];
    };
}

#pragma mark - UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return self.historyHeight;
    }
    return SCREENH_HEIGHT - self.historyHeight - Height_NavBar - 100;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (tableView == self.hotTable) {
        if (section == 0) {
            if (self.historyData.count < 1) {
                 return CGFLOAT_MIN;
            }
        }
        return 45;
    }
    return CGFLOAT_MIN;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (tableView == self.hotTable) {
        ASSearchTitleView *headV = [tableView dequeueReusableHeaderFooterViewWithIdentifier:ASSearchTitleViewStr];
        if (!headV) {
            headV = [[ASSearchTitleView alloc]initWithReuseIdentifier:ASSearchTitleViewStr];
        }
        if (section == 0) {
            if (self.historyData.count > 0) {
                headV.titleLab.hidden = NO;
                headV.clearBtn.hidden = NO;
            }else{
                headV.titleLab.hidden = YES;
                headV.clearBtn.hidden = YES;
            }
            headV.titleLab.text = @"最近搜索";
            [headV.clearBtn setTitle:@"清空" forState:UIControlStateNormal];
        }else{
            headV.titleLab.hidden = NO;
            headV.clearBtn.hidden = NO;
            headV.titleLab.text = @"热门搜索";
            [headV.clearBtn setTitle:@"" forState:UIControlStateNormal];
        }
        headV.index = section;
        headV.contentView.backgroundColor = self.view.backgroundColor;
        @weakify(self);
        headV.cleanBtnBlock = ^(NSInteger index) {
            @strongify(self);
            if (index == 0) {
                [self cleanAll];
            }else{
                [self loadMainData];
            }
        };
        return headV;
    }
    return [[UIView alloc]init];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    return [self hotSearchTableView:tableView cellForRowAtIndexPath:indexPath];
}

///热门搜索的相关cell
-(UITableViewCell *)hotSearchTableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ASSearchHotCell *cell = [tableView dequeueReusableCellWithIdentifier:ASSearchHotCellStr];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (indexPath.section == 0) {
        cell.type = SearchHotType_history;
        if (cell.dataArr.count < 1) {
            cell.dataArr = self.historyData;
        }
    }else{
        cell.type = SearchHotType_hot;
        if (cell.dataArr.count < 1) {
            cell.dataArr = self.hotTitleArr;
        }
    }
    @weakify(self);
    cell.clickSubSearchBlock = ^(NSString * _Nonnull searchContent, NSInteger index, SearchHotType subType) {
        @strongify(self);
        [self searchContent:searchContent];
    };
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
//    [self.headView.searchText resignFirstResponder];
//    if (tableView == self.searchTable) {
//        if (self.wordThinkList.count > 0) {
//            if (self.wordThinkList.count > indexPath.row) {
//                NSString *str = self.wordThinkList[indexPath.row];
//                [self searchContent:str];
//            }
//        }
//    }
}


- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == self.hotTable) {
        cell.contentView.backgroundColor = self.view.backgroundColor;
    }else{
        cell.contentView.backgroundColor = BACKGROUND_COLOR;
    }
}

///清除历史记录
- (void)cleanAll{
    [self.historyData removeAllObjects];
    self.historyData = [NSMutableArray new];
    [self crateHistoryHeight];
    //            [self.collectionView reloadSections:[NSIndexSet indexSetWithIndex:0]];
    [self.hotTable reloadData];
    [[NSUserDefaults standardUserDefaults]setObject:@[] forKey:SEARCHHISTORYKEY];
    [[NSUserDefaults standardUserDefaults]synchronize];
}

///计算历史搜索cell高度
- (void)crateHistoryHeight{
    self.historyHeight = CGFLOAT_MIN;
    NSInteger num = (NSInteger)self.historyData.count / 2;
    if (self.historyData.count % 2 > 0) {
        num += 1;
    }
    self.historyHeight = num*33;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
